from hashlib import md5
from binascii import a2b_hex, b2a_hex


def file_md5(file_name_or_url):
    file = None
    try:
        file_name = file_name_or_url
        index = file_name.rfind('/', )
        if index != -1:
            file_name = file_name_or_url[index: ]
        # print(file_name)
        path = __file__

        path = path[: path.find('/cmdb/')]
        path = path + '/static' + file_name

        # print(path)
        file = open(path, 'rb')
        mm = md5()
        content = b2a_hex(file.read())
        mm.update(content)
        return mm.hexdigest()

    except BaseException as e:
        return e.__str__()
    finally:
        if file:
            file.close()



# print(file_md5('http://www.qsong.ren/1.jpg'))
# print(file_md5('http://www.qsong.ren/2.jpg'))
# print(file_md5('http://www.qsong.ren/3.jpg'))
# print(file_md5('http://www.qsong.ren/4.png'))
# 1252d3de7366a16d3fc66aa3d860c3ab
# ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 0100010000ffdb004300